<template>
    <div>
        <el-card>
            <el-card>
                <el-form :inline="true">
                    <el-form-item>
                        <el-button type="primary" @click="showAddDialog">新增广告</el-button>
                    </el-form-item>
                </el-form>
            </el-card>

            <el-card style="margin-top: 20px">
                <el-table :data="contentData" border stripe v-loading="loading">
                    <el-table-column prop="sortOrder" label="序号" width="80"></el-table-column>
                    <el-table-column prop="title" label="广告名称"></el-table-column>
                    <el-table-column prop="categoryName" label="广告类型"></el-table-column>
                    <el-table-column prop="url" label="广告地址" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="pic" label="广告图片">
                        <template #default="scope">
                            <el-image :src="scope.row.pic" style="width: 60px; height: 30px" fit="contain"
                                :preview-src-list="[scope.row.pic]"></el-image>
                        </template>
                    </el-table-column>
                    <el-table-column prop="status" label="是否可见">
                        <template #default="scope">
                            <el-tag :type="scope.row.status ? 'success' : 'danger'">
                                {{ scope.row.status === '1' ? '可见' : '隐藏' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="180">
                        <template #default="scope">
                            <el-button size="small" type="warning" @click="showEditDialog(scope.row)">修改</el-button>
                            <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <el-pagination style="margin-top: 20px" v-model:current-page="pagination.current"
                    v-model:page-size="pagination.size" :total="pagination.total" @current-change="handlePageChange"
                    layout="total, prev, pager, next" />
            </el-card>
        </el-card>

        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
            <el-form :model="formData" label-width="100px" :rules="rules" ref="formRef">
                <el-form-item label="广告名称" prop="title">
                    <el-input v-model="formData.title"></el-input>
                </el-form-item>
                <el-form-item label="广告类型" prop="categoryId">
                    <el-select v-model="formData.categoryId" placeholder="请选择">
                        <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="广告链接" prop="url">
                    <el-input v-model="formData.url"></el-input>
                </el-form-item>
                <el-form-item label="广告图片" prop="pic">
                    <el-upload action="#" :auto-upload="false" :show-file-list="false" :on-change="handleUploadChange">
                        <el-button type="primary">选择图片</el-button>
                        <div v-if="formData.pic" class="preview-image">
                            <el-image :src="formData.pic" style="width: 100px; height: 60px"></el-image>
                        </div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="排序" prop="sortOrder">
                    <el-input-number v-model="formData.sortOrder" :min="1"></el-input-number>
                </el-form-item>
                <el-form-item label="是否可见" prop="status">
                    <el-switch v-model="formData.status" active-text="可见" inactive-text="隐藏"></el-switch>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">确认</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
    import {
        ref,
        reactive,
        onMounted
    } from 'vue'
    import {
        ElMessage,
        ElMessageBox
    } from 'element-plus'
    import {
        getContentAll,
        addContent,
        updateContent,
        deleteContent,
        getContentCategoryAll
    } from '../../api/ammanagement/index.js'

    const contentData = ref([])
    const categoryOptions = ref([])
    const loading = ref(false)
    const dialogVisible = ref(false)
    const dialogTitle = ref('新增广告')
    const formRef = ref(null)
    const file = ref(null)

    const formData = reactive({
        id: null,
        title: '',
        categoryId: '',
        url: '',
        pic: '',
        sortOrder: 1,
        status: true
    })

    const pagination = reactive({
        current: 1,
        size: 10,
        total: 0
    })

    const rules = {
        title: [{
            required: true,
            message: '请输入广告名称',
            trigger: 'blur'
        }],
        categoryId: [{
            required: true,
            message: '请选择广告类型',
            trigger: 'change'
        }],
        url: [{
            required: true,
            message: '请输入广告链接',
            trigger: 'blur'
        }]
    }

    const getList = async () => {
        try {
            loading.value = true
            const params = {
                pageNum: pagination.current,
                pageSize: pagination.size
            }
            const res = await getContentAll(params)
            contentData.value = res.list
            pagination.total = res.total

            const categories = await getContentCategoryAll()
            categoryOptions.value = categories

            contentData.value.forEach(item => {
                const category = categories.find(cat => cat.id === item.categoryId)
                item.categoryName = category ? category.name : '未知分类'
            })
        } catch (error) {
            console.error("获取数据失败：", error)
        } finally {
            loading.value = false
        }
    }

    const showAddDialog = () => {
        dialogTitle.value = '新增广告'
        resetForm()
        dialogVisible.value = true
    }

    const showEditDialog = (row) => {
        dialogTitle.value = '编辑广告'
        Object.assign(formData, row)
        dialogVisible.value = true
    }

    const resetForm = () => {
        formRef.value?.resetFields()
        formData.id = null
        formData.title = ''
        formData.categoryId = ''
        formData.url = ''
        formData.pic = ''
        formData.sortOrder = 1
        formData.status = true
        file.value = null
    }

    const handleUploadChange = (uploadFile) => {
        if (uploadFile) {
            file.value = uploadFile.raw;
            const reader = new FileReader();
            reader.onload = (e) => {
                formData.pic = e.target.result;
            };
            reader.readAsDataURL(file.value);
        } else {
            file.value = null;
        }
    };

    const submitForm = async () => {
        try {
            await formRef.value.validate();

            const form = new FormData();
            form.append('title', formData.title);
            form.append('categoryId', formData.categoryId);
            form.append('url', formData.url);
            form.append('sortOrder', formData.sortOrder.toString());
            form.append('status', formData.status ? '1' : '0');

            if (file.value) {
                form.append('contentpic', file.value);
            } else if (formData.id) {
                form.append('pic', formData.pic);
            }

            if (formData.id) {
                form.append('id', formData.id);
            }

            const res = formData.id ?
                await updateContent(form) :
                await addContent(form);

            if (typeof res === 'string' && res.startsWith('err')) {
                ElMessage.error(res.substring(4));
            } else {
                ElMessage.success(formData.id ? '修改成功' : '新增成功');
                dialogVisible.value = false;
                await getList();
            }
        } catch (error) {
            ElMessage.error('操作失败: ' + (error.message || '未知错误'));
        }
    };

    const handleDelete = async (id) => {
        try {
            await ElMessageBox.confirm('确定删除该广告吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            });

            const res = await deleteContent({
                id: id
            });

            if (res === 'deleteContent') {
                ElMessage.success('删除成功');
                await getList();
            } else if (res?.startsWith('err')) {
                ElMessage.error(res.substring(4));
            }
        } catch (error) {
            if (error !== 'cancel') {
                ElMessage.error(`删除失败: ${error.message || '未知错误'}`);
            }
        }
    };

    const handlePageChange = () => {
        getList()
    }

    onMounted(() => {
        getList()
    })
</script>

<style scoped>
    .preview-image {
        margin-top: 10px;
    }
</style>